﻿/*
 * 2008 (c) ralfoide at gmail com
 * Project: SharpFlow
 * License: GPL
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Alfray.SharpFlow.Utils {

    /// <summary>
    /// Utility class that creates a "singleton form".
    /// 
    /// For a given Form window, the window is only created when first visible
    /// and it's visibility can be toggled later (the window is just hidden).
    /// When the singleton is disposed, the window is closed.
    /// </summary>
    /// <typeparam name="F">An AutoSavingForm</typeparam>
    public class SingletonForm<F> : IDisposable where F : AutoSavingForm, new() {
        private F mSingleton;

        /// <summary>
        /// Creates the singleton form.
        /// The actual form is neither created nor visible at first.
        /// </summary>
        public SingletonForm() {
            mSingleton = null;
        }

        /// <summary>
        /// Creates the debug log form if necessary, makes it visible.
        /// </summary>
        public void open() {
            if (mSingleton == null) {
                mSingleton = new F();
                mSingleton.Visible = true;
                mSingleton.loadWindowPosition();
            }
        }

        /// <summary>
        /// Close (and disposes) the form if it was created.
        /// </summary>
        public void close() {
            if (mSingleton != null) {
                mSingleton.saveWindowPosition();
                mSingleton.Close();
                mSingleton.Dispose();
                mSingleton = null;
            }
        }

        /// <summary>
        /// Returns the visibility of the window, or false if it hasn't been created yet.
        /// </summary>
        public bool isVisible {
            get { return mSingleton == null ? false : mSingleton.Visible; }
        }

        /// <summary>
        /// Creates the form if necessary.
        /// Toggles its visibility.
        /// </summary>
        /// <returns>True if the window is now visible</returns>
        public bool toggleVisibility() {
            if (mSingleton == null) {
                open();
            } else {
                mSingleton.Visible = !mSingleton.Visible;
            }
            return mSingleton.Visible;
        }

        public F form {
            get {
                open();
                return mSingleton;
            }
        }

        #region IDisposable Members

        /// <summary>
        /// Disposing the SingletonForm closes the window if it was open
        /// and disposes it.
        /// </summary>
        public void Dispose() {
            close();
        }

        #endregion
    }
}
